package com.weixin.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * Created by Administrator on 2018-01-15.
 */
public class CheckUtil {
    public static final String tooken = "shenyuanchong";
    public static boolean checkSign(String signature,String timestamp,String nonce){
        //1.定义存放tooken,timestamp,nonce
        String[] arr = {tooken,timestamp,nonce};
        //2,对数组进行排序
        Arrays.sort(arr);
        //3，生成字符串
        StringBuffer sb = new StringBuffer();
        for(String s: arr){
            sb.append(s);
        }
        //4.sha1加密
        String temp=getSha1(sb.toString());
        //5,对比
        return temp.equals(signature);
    }

    public static String getSha1(String str) {
        if(str==null||str.length()==0){
            return null ;
        }
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j*2];
            int k = 0 ;
            for(int i= 0;i<j;i++){
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0>>>4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (NoSuchAlgorithmException e) {
            return null ;
        } catch (UnsupportedEncodingException e) {
            return null ;
        }

    }

}
